package com.cytech.cloudclinic.moudle.main.setting.prescription.drugs;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.cytech.cloudclinic.R;
import com.cytech.cloudclinic.adapter.PrescriptionAddDrugAdapter;
import com.cytech.cloudclinic.adapter.PrescriptionDrugMenuAdapter;
import com.cytech.cloudclinic.adapter.PrescriptionParentAdapter;
import com.cytech.cloudclinic.base.BaseActivity;
import com.cytech.cloudclinic.bean.CustomGroupDrug;
import com.cytech.cloudclinic.bean.CustomPrescriptionEntity;
import com.cytech.cloudclinic.bean.Drug;
import com.cytech.cloudclinic.bean.DrugTag;
import com.cytech.cloudclinic.bean.event.RefreshPresctiptionTemplate;
import com.cytech.cloudclinic.bean.req.AddPrescription;
import com.cytech.cloudclinic.dialog.AcuPointDialog;
import com.cytech.cloudclinic.dialog.AddDoctorOrderDialog;
import com.cytech.cloudclinic.dialog.EditDrugBodyPointDialog;
import com.cytech.cloudclinic.dialog.EditDrugDefaultDialog;
import com.cytech.cloudclinic.dialog.EditDrugTimeDialog;
import com.cytech.cloudclinic.dialog.SelectUseAndDayDialog;
import com.yechaoa.yutils.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 处方模板药品
 */
public class PrescriptionDrugActivity extends BaseActivity<PrescriptionDrugPresenter> implements PrescriptionDrugView {
    @BindView(R.id.titlebar_title)
    TextView tvTitle;

    @BindView(R.id.rv_menu_drug_tag)
    RecyclerView menuTagRv;
    @BindView(R.id.rv_prescription_drug)
    RecyclerView drugRv;
    @BindView(R.id.rv_prescription_parent)
    RecyclerView parentRv;

    private List<DrugTag> drugTags;
    private List<Drug> drugList;
    private List<CustomPrescriptionEntity> parentList;

    private PrescriptionDrugMenuAdapter drugMenuAdapter;
    private PrescriptionAddDrugAdapter drugAdapter;
    private PrescriptionParentAdapter parentAdapter;
    //药品分类id
    private int drugParentTagId;
    //处方分类id
    private String prescription_type;
    //处方名称
    private String templateName;

    //处方id
    private String prescriptionId;
    private int currentGroup = 0;
    //处方筏对应组下面的药品
    private int currentChildPos;
    private List<CustomPrescriptionEntity> editDrugList;

    /**
     *
     * @param context
     * @param drugParentTagId  药品分类id
     * @param prescription_type  处方模板分类id
     * @param templateName 处方名称
     */
    public static void actionStart(Context context,int drugParentTagId,String prescription_type,String templateName){
        Intent intent = new Intent(context,PrescriptionDrugActivity.class);
        intent.putExtra("drugParentTagId",drugParentTagId);
        intent.putExtra("prescription_type",prescription_type);
        intent.putExtra("templateName",templateName);
        context.startActivity(intent);
    }

    /**
     *编辑药品
     * @param context
     * @param drugParentTagId  药品分类id
     * @param prescription_type  处方模板分类id
     * @param prescriptionId 处方id
     * @param templateName 处方名称
     */
    public static void actionStart(Context context,int drugParentTagId,String prescription_type,String templateName,String prescriptionId,List<CustomPrescriptionEntity> entity){
        Intent intent = new Intent(context,PrescriptionDrugActivity.class);
        intent.putExtra("drugParentTagId",drugParentTagId);
        intent.putExtra("prescription_type",prescription_type);
        intent.putExtra("prescriptionId",prescriptionId);
        intent.putExtra("templateName",templateName);
        Bundle bundle = new Bundle();
        bundle.putSerializable("customPrescriptionEntity", (Serializable) entity);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    @Override
    protected PrescriptionDrugPresenter createPresenter() {
        return new PrescriptionDrugPresenter(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.act_prescrition_drug;
    }

    @Override
    protected void initView() {
        tvTitle.setText("添加模板");
    }

    @Override
    protected void initData() {
        drugParentTagId = getIntent().getIntExtra("drugParentTagId",0);
        prescription_type = getIntent().getStringExtra("prescription_type");
        prescriptionId = getIntent().getStringExtra("prescriptionId");
        templateName = getIntent().getStringExtra("templateName");
        Bundle bundle = getIntent().getExtras();
        if(bundle!=null){
            editDrugList = (List<CustomPrescriptionEntity>) bundle.getSerializable("customPrescriptionEntity");
        }
        initDrugMenuRv();

        initDrugListRV();

        initParentRv();


        //编辑药品
        if(editDrugList!=null){
            parentAdapter.setNewInstance(editDrugList);
        }

        presenter.getDrugTagList(drugParentTagId);
    }

    /**
     * 初始化药品分类标签
     */
    private void initDrugMenuRv() {
        drugTags = new ArrayList<>();
        drugMenuAdapter = new PrescriptionDrugMenuAdapter(drugTags);
        menuTagRv.setLayoutManager(new LinearLayoutManager(this));
        menuTagRv.setAdapter(drugMenuAdapter);
        drugMenuAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                drugMenuAdapter.setCurrentPos(position);
                presenter.getDrugList("", drugMenuAdapter.getItem(position).tag_id);
            }
        });
    }

    /**
     * 初始化药品列表
     */
    private void initDrugListRV() {
        drugList = new ArrayList<>();
        drugAdapter = new PrescriptionAddDrugAdapter(drugList);
        drugRv.setLayoutManager(new LinearLayoutManager(this));
        drugRv.setAdapter(drugAdapter);

        drugAdapter.addChildClickViewIds(R.id.tv_prescription_add_drug);
        drugAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                //TODO 这里应该判断药品列表中如果存在同样的药品id，数量加1
                Drug drug = drugAdapter.getItem(position);
                drug.cont_unit_text = drug.subunit_text;
                if (parentAdapter.getItemCount() == 0) {
                    //0的话新增一个分组，最后一个的话也新增一个分组
                    CustomPrescriptionEntity newItem = new CustomPrescriptionEntity();
                    newItem.drugList.add(drugAdapter.getItem(position));
                    parentAdapter.addData(newItem);
                    parentAdapter.addData(new CustomPrescriptionEntity());
                } else {
                    //判断是否是新增的数据
                    boolean isNewAdd = true;
                    int existPos = -1;
                    List<Drug> currentGroupDrug = parentAdapter.getItem(currentGroup).drugList;
                    for (int i = 0; i < currentGroupDrug.size(); i++) {
                        //存在相同的id，数量加1即可，不必添加新的item
                        if (drug.drug_id == currentGroupDrug.get(i).drug_id) {
                            existPos = i;
                            isNewAdd = false;
                            break;
                        }
                    }
                    if (!isNewAdd) {
                        //列表里面已经有数据了
                        currentGroupDrug.get(existPos).count += 1;
                        parentAdapter.notifyItemChanged(currentGroup);
                    } else {
                        if (currentGroup == parentAdapter.getItemCount() - 1) {
                            parentAdapter.addData(new CustomPrescriptionEntity());

                            parentAdapter.getItem(currentGroup).drugList.add(drugAdapter.getItem(position));
                            parentAdapter.notifyItemChanged(currentGroup);
                        } else {
                            //添加药品到对于的适配器中
                            parentAdapter.getItem(currentGroup).drugList.add(drugAdapter.getItem(position));
                            parentAdapter.notifyItemChanged(currentGroup);
                        }
                    }
                }
            }
        });
    }


    /**
     * 初始化处方筏父标签（分组标签）
     */
    private void initParentRv() {
        parentList = new ArrayList<>();
        parentAdapter = new PrescriptionParentAdapter(parentList, presenter.isShowAcupoint(drugParentTagId), drugParentTagId,new PrescriptionParentAdapter.OnChildClickListener() {
            @Override
            public void acupointClick(int parentPos, int childPos) {
                currentGroup = parentPos;
                currentChildPos = childPos;
                //presenter.getAcuPoint(false,0,drugParentTagId,true);
                //弹出穴位选择弹窗
                AcuPointDialog acuPointDialog = new AcuPointDialog(drugParentTagId, parentAdapter.getItem(parentPos).drugList.get(childPos), new AcuPointDialog.OnSaveAcuPointListener() {
                    @Override
                    public void onSave(String acupointStr) {
                        parentAdapter.getItem(parentPos).drugList.get(childPos).acupoints.acupoint_name = acupointStr;
                        parentAdapter.notifyItemChanged(parentPos);
                    }
                });
                acuPointDialog.show(getSupportFragmentManager(), "acupoint");
            }

            @Override
            public void acupointTime(int parentPos, int childPos) {
                EditDrugTimeDialog timeDialog = new EditDrugTimeDialog(drugParentTagId, parentAdapter.getItem(parentPos).drugList.get(childPos), new EditDrugTimeDialog.OnSaveClickListener() {
                    @Override
                    public void onSave(Drug drug) {
                        Drug oldDrug = parentAdapter.getItem(parentPos).drugList.get(childPos);
                        oldDrug.acupoints.acupoint_number = drug.acupoints.acupoint_number;
                        oldDrug.acupoints.acupoint_name = drug.acupoints.acupoint_name;
                        parentAdapter.notifyItemChanged(parentPos);
                    }
                });
                timeDialog.show(getSupportFragmentManager(), "drugTime");
            }

            @Override
            public void drugItemClick(int parentPos, int childPos) {
                EditDrugDefaultDialog editDrugDialog = new EditDrugDefaultDialog(drugParentTagId, parentAdapter.getItem(parentPos).drugList.get(childPos), new EditDrugDefaultDialog.OnSaveClickListener() {
                    @Override
                    public void onSave(Drug drug) {
                        Drug oldDrug = parentAdapter.getItem(parentPos).drugList.get(childPos);
                        oldDrug.number = drug.number;
                        oldDrug.usage_mode = drug.usage_mode;
                        oldDrug.dosage = drug.dosage;
                        oldDrug.frequency = drug.frequency;
                        parentAdapter.notifyItemChanged(parentPos);
                    }
                });
                editDrugDialog.show(getSupportFragmentManager(), "editdrug");
            }

            @Override
            public void bodyPointClick(int parentPos, int childPos) {
                //体位
                EditDrugBodyPointDialog editDrugDialog = new EditDrugBodyPointDialog(drugParentTagId, parentAdapter.getItem(parentPos).drugList.get(childPos), new EditDrugBodyPointDialog.OnSaveClickListener() {
                    @Override
                    public void onSave(Drug drug) {
                        Drug oldDrug = parentAdapter.getItem(parentPos).drugList.get(childPos);
                        oldDrug.bodyPoint = drug.bodyPoint;
                        oldDrug.bodyPointTimes = drug.bodyPointTimes;
                        parentAdapter.notifyItemChanged(parentPos);
                    }
                });
                editDrugDialog.show(getSupportFragmentManager(), "editdrug");
            }
        });
        parentRv.setLayoutManager(new LinearLayoutManager(this));
        parentRv.setAdapter(parentAdapter);
        parentAdapter.addChildClickViewIds(R.id.ll_item_prescription_group, R.id.item_doctor_order,R.id.ll_item_day_number);
        parentAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                switch (view.getId()) {
                    case R.id.ll_item_prescription_group:
                        currentGroup = position;
                        parentAdapter.setCurrentPos(position);
                        presenter.getDrugTagList(drugParentTagId);
                        break;
                    case R.id.item_doctor_order:
                        AddDoctorOrderDialog doctorOrderDialog = new AddDoctorOrderDialog(new AddDoctorOrderDialog.OnSaveDoctorListener() {
                            @Override
                            public void onSave(String doctorOrderStr) {
                                parentAdapter.getItem(position).doctorOrder = doctorOrderStr;
                                parentAdapter.notifyItemChanged(position);
                            }
                        });
                        doctorOrderDialog.show(getSupportFragmentManager(), "doctorOrder");
                        break;
                    case R.id.ll_item_day_number:   //用法，天数，次数
                        SelectUseAndDayDialog useAndDayDialog = new SelectUseAndDayDialog(drugParentTagId);
                        useAndDayDialog.show(getSupportFragmentManager(),"use_day");
                        break;
                }

            }
        });
    }

    @Override
    public void getDrugChildTagSuccess(List<DrugTag> data) {
        drugMenuAdapter.setNewInstance(data);
        if (data != null && data.size() > 0) {
            presenter.getDrugList("", data.get(0).tag_id);
        }
    }

    @Override
    public void getDrugSuccess(List<Drug> data) {
        drugAdapter.setNewInstance(data);
    }

    @OnClick({R.id.titlebar_back,R.id.btn_prescription_cancel})
    public void exit(View view){
        finish();
    }

    @OnClick(R.id.btn_prescription_temp_save)
    public void save(View view){
        //添加处方模板
        AddPrescription addPrescription = new AddPrescription();
        addPrescription.diagnose = templateName;
        addPrescription.prescription_type = prescription_type;
        addPrescription.prescription_id = prescriptionId;
        addPrescription.status = 3;
        addPrescription.drug_tag = drugParentTagId;
        List<CustomPrescriptionEntity> templateDrugList = parentAdapter.getData();
        for (int i = 0; i < templateDrugList.size(); i++) {
            if (templateDrugList.get(i).drugList != null && templateDrugList.get(i).drugList.size() > 0) {
                CustomGroupDrug groupDrug = new CustomGroupDrug();
                groupDrug.doctors_advice = templateDrugList.get(i).doctorOrder;
                groupDrug.list = templateDrugList.get(i).drugList;
                addPrescription.drugs.add(groupDrug);
            }
        }

        presenter.addPrescription(addPrescription,true);
    }

    @Override
    public void addPrescriptionSuccess() {
        //开方成功
        ToastUtil.showToast("处方创建成功");
        EventBus.getDefault().post(new RefreshPresctiptionTemplate());
        finish();
    }
}
